import matplotlib.pyplot as plt
import numpy as np

# 支持中文
plt.rcParams['font.family'] = ['sans-serif']
plt.rcParams['font.sans-serif'] = ['SimHei']
# 支持负数
plt.rcParams['axes.unicode_minus'] = False

# 设置图形
fig, ax = plt.subplots(figsize=(10, 8))

# 椭圆参数 (x^2 + 2y^2 = 2 => x^2/2 + y^2/1 = 1)
a = np.sqrt(2)
b = 1

# 绘制椭圆
theta = np.linspace(0, 2*np.pi, 100)
x_ellipse = a * np.cos(theta)
y_ellipse = b * np.sin(theta)
ax.plot(x_ellipse, y_ellipse, 'b-', label='椭圆: $x^2 + 2y^2 = 2$')

# 原点
ax.plot(0, 0, 'ko', markersize=6, label='原点O')
ax.text(0.1, 0.1, 'O', fontsize=12)

# 轨迹圆 (D点的轨迹)
theta_circle = np.linspace(0, 2*np.pi, 100)
r = np.sqrt(2/3)
x_circle = r * np.cos(theta_circle)
y_circle = r * np.sin(theta_circle)
ax.plot(x_circle, y_circle, 'r--', label='D点轨迹: $x^2+y^2=2/3$')

# 示例点
# 在轨迹圆上取几个点展示
theta_d = [np.pi/6, np.pi/3, 2*np.pi/3, 5*np.pi/6]
for angle in theta_d:
    x_d = r * np.cos(angle)
    y_d = r * np.sin(angle)
    ax.plot(x_d, y_d, 'mo', markersize=6)
    
    # 绘制垂线OD
    ax.plot([0, x_d], [0, y_d], 'g--', alpha=0.5)
    
    # 标记D点
    ax.text(x_d+0.1, y_d+0.1, 'D', fontsize=10)

# 设置图形属性
ax.set_xlim(-1.5, 1.5)
ax.set_ylim(-1.2, 1.2)
ax.set_aspect('equal')
ax.grid(True, alpha=0.3)
ax.axhline(y=0, color='k', linewidth=0.5)
ax.axvline(x=0, color='k', linewidth=0.5)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title('例题4: 椭圆上动点的垂足轨迹问题')
ax.legend()

plt.tight_layout()
plt.show()